package com.biz.primus.ms.order.service.impl;

import com.biz.primus.base.exception.BizSilentException;
import com.biz.primus.base.exception.utils.AssertUtils;
import com.biz.primus.model.oms.stream.OrderStateChannel;
import com.biz.primus.model.order.enums.CommentState;
import com.biz.primus.model.order.enums.DeliveryState;
import com.biz.primus.model.order.enums.OrderState;
import com.biz.primus.model.order.exception.OrderException;
import com.biz.primus.model.order.exception.utils.AssertRequestParameter;
import com.biz.primus.model.order.vo.request.OrderSummaryRequestVO;
import com.biz.primus.model.order.vo.request.PaidOrderRequestVO;
import com.biz.primus.model.order.vo.aftersale.QueryOrderResponseVO;
import com.biz.primus.model.order.vo.response.OrderResponseVO;
import com.biz.primus.model.order.vo.response.OrderSummaryResponseVO;
import com.biz.primus.ms.order.convertor.OrderConvertor;
import com.biz.primus.ms.order.dao.po.Order;
import com.biz.primus.ms.order.dao.po.OrderSummary;
import com.biz.primus.ms.order.service.OrderService;
import com.biz.primus.ms.order.service.bulider.CancelOrderBuilder;
import com.biz.primus.ms.order.service.bulider.CreateOrderBuilder;
import com.biz.primus.ms.order.service.bulider.PaidOrderBuilder;
import com.biz.primus.ms.order.service.bulider.SettleOrderBuilder;
import com.biz.primus.ms.order.service.helper.OrderDataStreamHelper;
import com.biz.primus.ms.order.service.helper.OrderServiceHelper;
import com.biz.primus.ms.order.service.helper.OrderStateStreamHelper;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;

/**
 * 订单服务,
 * 秒杀订单促销使用有效期5分钟
 *
 * @author Tiger Feng
 * @date 2017年10月30日
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderServiceHelper orderServiceHelper;
    @Autowired
    private OrderStateStreamHelper orderStateStreamHelper;
    @Autowired
    private OrderDataStreamHelper orderDataStreamHelper;


    /**
     * 订单结算<br><p>
     * 1.配送地址：用户收货地址；<br>
     * 2.配送方式：同城配送、自提、三方物流；<br>
     * 3.商品促销活动：活动方式去人（商品A送商品B、满x减y）；<br>
     * 4.订单促销活动：<br>
     * 5.优惠券：调用第三方接口计算；<br>
     * 6.支付方式：线上统一（货到付款、微信支付、支付宝支付、电子钱包、银行卡）；<br>
     * 7.发票说明：记录发票信息；<br></p>
     *
     * @param requestVO 订单汇总对象
     * @return 汇总后的订单数据
     */
    @Override
    public OrderSummaryResponseVO settleOrder(OrderSummaryRequestVO requestVO) {
        SettleOrderBuilder settleOrderBuilder = SettleOrderBuilder.newBuilder(requestVO, orderServiceHelper)
                .check()
                .handlePaymentWay()
                .handleStoreOrder()
                .handleFlagshipOrder()
                .handlePromotionAndDelivery();
        return settleOrderBuilder.build();
    }

    /**
     * 创建订单<br>
     * 1、订单结算；
     * 2、创建订单，持久化；
     * 3、锁定库存；
     * 4、消费优惠券；
     * 5、使用促销；
     *
     * @param requestVO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderSummaryResponseVO createOrder(OrderSummaryRequestVO requestVO) {
        OrderSummaryResponseVO settleOrderSummary = SettleOrderBuilder.newBuilder(requestVO, orderServiceHelper)
                .check()
                .handlePaymentWay()
                .handleStoreOrder()
                .handleFlagshipOrder()
                .handlePromotionAndDelivery()
                .build();
        return CreateOrderBuilder.newBuilder(settleOrderSummary, orderServiceHelper)
                .saveOrder()
                .usePromotion()
                .useCoupon()
                .build();
    }

    @Override
    public OrderResponseVO getByOrderCode(String orderCode) {
        return OrderConvertor.po2ResponseVO(orderServiceHelper.getByOrderCode(orderCode));
    }

    @Override
    public List<OrderResponseVO> getByOrderCodeAndState(String orderCode, OrderState state) {
        return orderServiceHelper.getByOrderCodeAndState(orderCode, state);
    }

    @Override
    public Boolean updateOrderSummary2Paid(PaidOrderRequestVO paidOrderRequestVO) {
        PaidOrderBuilder paidOrderBuilder = PaidOrderBuilder.newBuilder(
                paidOrderRequestVO,
                orderServiceHelper,
                orderDataStreamHelper);
        boolean callback = false;
        try {
            OrderSummary orderSummary = paidOrderBuilder.updateLocalOrderState().sendOMS().build();
            callback = (orderSummary != null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return callback;
    }

    @Override
    public void cancelOrder(String orderCode) {
        CancelOrderBuilder builder = CancelOrderBuilder.newBuilder(
                orderServiceHelper.getByOrderCode(orderCode),
                orderServiceHelper,
                orderStateStreamHelper);
        builder.check().cancel();
    }

    @Override
    public Boolean confirmReceipt(String orderCode) {
        AssertRequestParameter.hasText(orderCode, "订单编码不能为空");
        Order order = orderServiceHelper.getByOrderCode(orderCode);
        AssertUtils.notNull(order, OrderException.ORDER_NOT_EXIST);
        switch (order.getState()) {
            case WAIT_PAY:
                throw new BizSilentException(OrderException.PLEASE_PAY);
            case WAIT_SEND:
                throw new BizSilentException(OrderException.STATE_ERROR);
            case WAIT_RECEIVE:
                break;
            case WAIT_EVALUATION:
                throw new BizSilentException(OrderException.STATE_ERROR);
            case FINISHED:
                return true;
            case CANCELED:
                throw new BizSilentException(OrderException.STATE_ERROR);
            case AFTER_SALE:
                throw new BizSilentException(OrderException.STATE_ERROR);
            case FINISHED_AFTER_SALE:
                throw new BizSilentException(OrderException.STATE_ERROR);
            default:
                throw new BizSilentException(OrderException.STATE_ERROR);
        }
        Timestamp now = new Timestamp(System.currentTimeMillis());
        // 签收时间
        order.getDelivery().setReceiveTimestamp(now);
        // 物流状态
        order.getDelivery().setDeliveryState(DeliveryState.SIGNED);
        // 订单状态
        order.setState(OrderState.FINISHED);
        // 评价状态
        order.setCommentState(CommentState.WAITING_COMMENTS);
        order.setUpdateTimestamp(now);
        orderServiceHelper.saveOrder(order);
        try {
            // 给OMS发送用户确认收货 -- 接口
            orderStateStreamHelper.sendUserFinishOrder(order);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
